<template>
	<view class="page">
		<cl-nav-bar>
			<template #right>
				<view v-if="curType === 'list'" class="import_btn" @click="handleStartSelect">
					批量导出
				</view>
				<view v-if="curType === 'select'" class="import_btn" @click="handleCancelSelect">
					取消
				</view>
			</template>
		</cl-nav-bar>
		<view class="page_search">
			<uni-search-bar v-model.trim="keyword" cancelButton="none" radius="30" placeholder="请输入关键字查询">
			</uni-search-bar>
		</view>
		<view class="page_content" v-if="filterFillList.length > 0">
			<view v-for="item in filterFillList" :key="item.fillId" class="template_item" @click="handleAddOrEdit(item)">
				<!-- <image
          src="../../static/template_icon.png"
          class="template_item_icon"
          mode="scaleToFill"
        /> -->
				<view v-html="highlightKeywords(item.name)" class="exceed_omit1" style="margin-right: 40rpx;"></view>
				<text style="margin-left: auto;flex-shrink: 0;">{{item.pushTime}}</text>
				<image v-if="curType === 'list'" src="../../static/del_icon.png" class="del_icon" mode="scaleToFill"
					@click.stop="handleDel(item)" />
				<image v-if="curType === 'select'"
					:src="selectList.some(itm => itm.fillId === item.fillId) ? '../../static/selected-icon.png' : '../../static/no-select.png'"
					class="del_icon" mode="scaleToFill" />
			</view>
		</view>
		<empty v-else></empty>
		<view class="g_bottom_box" style="display: flex;">
			<view class="g_bottom_box_btn" @click="handleAddOrEdit"> 新增填报 </view>
			<view v-if="curType === 'select' && selectList.length > 0" class="g_bottom_box_btn"
				style="margin-left: 20rpx;" @click="handlePreview"> 导出预览 </view>
		</view>
	</view>
	<uni-popup ref="popupRef" type="center">
		<view class="paf_preview">
			<view class="paf_preview_content" :id="'pdfPreview' + index"
				v-for="(formData, index) in selectDataFormDataList" :key="formData.fillId">
				<view class="paf_preview_content_title">
					{{formData.fillTitle}}
				</view>
				<view>
					基本信息
				</view>
				<view class="field_item" v-for="field in baseFieldList" :key="field.value">
					<view class="field_item_label">{{ field.label }}：</view>
					<view class="field_item_value">{{formData[field.value]}}</view>
				</view>
				<view>
					模板信息
				</view>
				<template v-for="temp in templateData.fieldList" :key="temp.field_id">
					<view class="field_item" v-if="
	          ['input', 'numberInput', 'date', 'select'].includes(temp.type)
	        ">
						<view class="field_item_label">{{ temp.label }}：</view>
						<view class="field_item_value">
							{{
	            Array.isArray(formData[temp.field_id])
	              ? formData[temp.field_id].join('、')
	              : formData[temp.field_id]
	          }}
						</view>
					</view>
					<view v-else-if="temp.type === 'upImage'">
						<view class="field_item_img_label">{{ temp.label }}：</view>
						<img class="field_item_img_value" v-for="itm in formData[temp.field_id]" :key="itm.url"
							:src="itm.b64Data" mode="widthFix" />
					</view>
				</template>
			</view>
			<view class="paf_preview_bottom">
				<view class="paf_preview_bottom_btn" @click="handleSavePDF">保存为</view>
			</view>
		</view>
		<sp-html2pdf-render :key="pdfContentId" :autoOpen="false" :domId="pdfContentId" ref="renderRef" :showLoading="true" afterSavePDF="afterSavePDF"
			 :pdfFileName="pdfFileName" @afterSavePDF="afterSavePDF"></sp-html2pdf-render>
	</uni-popup>
</template>

<script setup>
	import {
		pathToBase64,
		getLocalFilePath,
	} from '../../uni_modules/sp-html2pdf-render/utils'
	import {
		getTemplateList,
		setTemplateList
	} from '@/utils/store.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getOrCreateDir,
		getDirList,
		removeDir,
		getJsonData,
		checkImage
	} from '../../utils/file'
import { nextTick } from 'vue'

	const fillList = ref([])
	const tempalteId = ref()
	const popupRef = ref()
	const tempalteDirName = ref('')
	const templateData = ref({
		name: '',
		templateId: '',
		fieldList: [],
	})
	const curType = ref('list')
	const selectList = ref([])
	const selectDataFormDataList = ref([])
	const baseFieldList = [{
			label: '填报人',
			value: 'creator'
		},
		{
			label: '填报人电话',
			value: 'creatorTel'
		},
		{
			label: '项目型号',
			value: 'projectModel'
		},
		{
			label: '批次号',
			value: 'batchNumber'
		},
		{
			label: '数量',
			value: 'number'
		},
		{
			label: '老化地点',
			value: 'agingAddress'
		}, {
			label: '开始时间',
			value: 'startDate'
		}, {
			label: '工时',
			value: 'workDate'
		}, {
			label: '结束时间',
			value: 'endDate'
		}
	]
	const handleStartSelect = () => {
		curType.value = 'select'
		selectList.value = []
	}
	const handleCancelSelect = () => {
		curType.value = 'list'
		selectList.value = []
	}
	// 图片转b64格式展示
	const toB64Show = async (formData) => {
		let imgFieldIds = templateData.value.fieldList
			.filter((item) => item.type === 'upImage')
			.map((item) => item.field_id)
		for (const fieldId of imgFieldIds) {
			for (const imgItem of formData[fieldId] || []) {
				imgItem.b64Data = await pathToBase64(getLocalFilePath(imgItem.url))
			}
		}
	}
	const handlePreview = async () => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		const res = await Promise.all(selectList.value.map(item => {
			return getJsonData(
				`_doc/templateList/${tempalteDirName.value}/fillList/${item.dirName}/fillData.json`
			)
		})).catch(err => {
			console.log(err, 'err');
			uni.showToast({
				title: '加载失败，请重试！',
				icon: 'none',
				mask: true
			})
		}).finally(() => {
			uni.hideLoading()
		})
		const resFormDataList = res.map((item, index) => {
			let data = JSON.parse(item.result)
			data['fillTitle'] = selectList.value[index]['name']
			return data
		})
		for (let formData of resFormDataList) {
			const checkFlag = await checkImage(templateData.value, formData)
			if (!checkFlag) {
				return uni.showToast({
					title: `所选数据《${formData.title}》 图片缺失，请重新上传！`,
					icon: 'none',
					mask: true,
					duration:3000
				})
			}
			await toB64Show(formData)
		}
		selectDataFormDataList.value = resFormDataList
		popupRef.value.open()
	}
	
	const pdfFileName = ref('')
	const pdfContentId = ref('pdfPreview0')
	const curPdf = ref(0)
	const renderRef = ref()
	// pdf保存
	const handleSavePDF = async () => {
		curPdf.value = 0
		pdfContentId.value = 'pdfPreview' + curPdf.value
		// 因为电脑不识别空格跟冒号的文件名
		const formData = selectDataFormDataList.value[curPdf.value]
		let newDate = formData.startDate.replace(' ', '_').replace(':', '-')
		pdfFileName.value = `${formData.projectModel}_${formData.batchNumber}_${newDate}`
		renderRef.value.h2pRenderDom()
	}
	
	const afterSavePDF = async () => {
		if (selectDataFormDataList.value.length === curPdf.value + 1) {
			popupRef.value.close()
			uni.showToast({
				title:'导出完成！',
				icon: 'success'
			})
			curType.value = 'list'
			return uni.hideLoading()
		}
		curPdf.value ++
		pdfContentId.value = 'pdfPreview' + curPdf.value
		await nextTick()
		const formData = selectDataFormDataList.value[curPdf.value]
		let newDate = formData.startDate.replace(' ', '_').replace(':', '-')
		pdfFileName.value = `${formData.projectModel}_${formData.batchNumber}_${newDate}`
		renderRef.value.h2pRenderDom()
	}

	onLoad(async (options) => {
		if (options.dirName) {
			tempalteDirName.value = options.dirName
			await getOrCreateDir(`_doc/templateList/${options.dirName}/fillList`, true)
			getFillList()
			const res = await getJsonData(
				`_doc/templateList/${tempalteDirName.value}/templateData.json`
			)
			templateData.value = JSON.parse(res.result)
		}
	})

	// 获取填报列表数据
	const getFillList = async () => {
		const res = await getDirList(
			`_doc/templateList/${tempalteDirName.value}/fillList`
		)
		fillList.value = res.map((dirName) => {
			let arr = dirName.split('␟')
			if (arr.length === 3) {
				return {
					name: arr[2],
					fillId: arr[0],
					dirName,
					pushTime: arr[1]
				}
			} else {
				return {
					name: '错误数据，请排除',
				}
			}
		}).sort((a, b) => new Date(b.pushTime) - new Date(a.pushTime));
	}

	const keyword = ref('')
	// 过滤列表
	const filterFillList = computed(() => {
		return fillList.value.filter((item) => item.name.includes(keyword.value))
	})
	// 高亮展示
	const highlightKeywords = (text) => {
		if (keyword.value.length === 0) {
			return `<span>${text}</span>`
		}
		const reg = new RegExp(keyword.value, 'g')
		return text.replace(reg, `<span style="color: red">${keyword.value}</span>`)
	}

	// 删除
	const handleDel = (data) => {
		uni.showModal({
			title: '提示',
			content: '确认删除该填报数据？',
			showCancel: true,
			success: async ({
				confirm
			}) => {
				if (confirm) {
					await removeDir(
						`_doc/templateList/${tempalteDirName.value}/fillList/${data.dirName}`
					)
					uni.showToast({
						title: '删除成功！',
						duration: 500,
						success: () => {
							getFillList()
						},
					})
				}
			},
		})
	}

	const handleAddOrEdit = (data) => {
		if (curType.value === 'select') {
			const idx = selectList.value.findIndex(item => item.fillId === data.fillId)
			if (idx > -1) {
				selectList.value.splice(idx, 1)
			} else {
				selectList.value.push(data)
			}
			console.log(selectList.value);
			return
		}
		uni.navigateTo({
			url: '/pages/fill/index',
			events: {
				acceptDataFromOpenedPage: () => {
					getFillList()
				},
			},
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					tempalteDirName: tempalteDirName.value,
					fillDirName: data?.dirName,
				})
			},
		})
		// uni.navigateTo({
		//   url: `/pages/fill/index?templateId=${tempalteId.value}`,
		// })
	}
</script>

<style lang="scss" scoped>
	.page {
		display: flex;
		flex-direction: column;
		height: 100%;

		&_search {
			background-color: #fff;
		}

		&_content {
			margin-top: 20rpx;
			flex: 1;

			.template_item {
				margin-bottom: 4rpx;
				padding: 28rpx;
				display: flex;
				align-items: center;
				background-color: #fff;

				&_icon {
					margin-right: 40rpx;
					flex-shrink: 0;
					width: 50rpx;
					height: 50rpx;
				}

				.del_icon {
					flex-shrink: 0;
					margin-left: 20rpx;
					width: 50rpx;
					height: 50rpx;
				}
			}
		}
	}

	.import_btn {
		font-size: 28rpx;
		color: $uni-color-primary;
	}

	.paf_preview {
		position: relative;
		box-sizing: border-box;
		background-color: #fff;
		width: 90vw;
		max-height: 80vh;
		overflow-y: auto;
		border-radius: 10rpx;

		&_content {
			width: 1000rpx;
			margin: 20rpx 0;
			padding: 40rpx;
			height: max-content;
			overflow-y: auto;
			&_title {
				padding: 20rpx 0;
				font-size: 32rpx;
				font-weight: bold;
				text-align: center;
			}

			.field_item {
				margin: 20rpx 0;
				display: flex;
				align-items: center;

				&_label {
					font-weight: bold;
					flex-shrink: 0;
					width: 8rem;
					text-align: right;
				}

				&_right {
					margin-left: 40rpx;
				}
			}

			.field_item_img {
				&_label {
					font-weight: bold;
					flex-shrink: 0;
					width: 8rem;
					text-align: right;
				}

				&_value {
					margin-top: 20rpx;
					width: 100%;
					page-break-before: always;
					/* 强制在图片前分页 */
					page-break-after: always;
					/* 强制在图片后分页 */
					page-break-inside: avoid;
					/* 确保图片本身不被分割 */
					text-align: center;
					/* 图片居中显示 */
					padding: 20px;
				}
			}
		}

		&_bottom {
			padding: 20rpx;
			position: sticky;
			bottom: 0;
			left: 0;
			box-sizing: border-box;
			width: 100%;
			background-color: #fff;

			&_btn {
				padding: 20rpx;
				box-sizing: border-box;
				margin: auto;
				width: 60%;
				text-align: center;
				border-radius: 40rpx;
				color: #fff;
				background-color: $uni-color-primary;
			}
		}
	}
</style>